﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Drawing;
using DirectUI.Mobile.UI.Native;
using DirectUI.Mobile.UI.Drawing.GdiPlus;
using System.Diagnostics;

namespace DirectUI.Mobile.UI.Controls
{
    /// <summary>
    /// Default class for IControlContainer controls.
    /// </summary>
    public class ControlContainer : DirectUIControl, IMultiControlContainer, ICommandContainer
    {
        public ControlContainer()
            : base()
        { }

        public ControlContainer(int x, int y, int width, int height)
            : base(x, y, width, height)
        {
        }

        public override void DataBind()
        {
            base.DataBind();
         
            for (int i = 0; i < Controls.Count; i++)
            {
                DirectUIControl c = Controls[i];
                if (c.NeedDataBind)
                {
                    c.DataBind();
                }
            }
            NeedDataBind = false;
        }
        protected override void InitControl()
        {
            base.InitControl();
            Init();
        }
        public override bool Initializing
        {
            get
            {
                if (initializing) return true;
                DirectUIControl parent = Parent;
                if (parent != null) return parent.Initializing;
                if (parent == null && host == null)
                {
                    return true;
                }
                return false;
            }
        }
        private void Init()
        {
            controls = new DirectUIControlCollection(this);
            ForeColor = Color.Empty;
            this.NeedDataBind = true;
         
        }

 
        #region IControlContainer Members

        internal DirectUIControlCollection controls;
        private readonly object lockObject = new object();
        public DirectUIControlCollection Controls { get {
           
                return controls;
            
        } }
        public override void Dispose()
        {
            base.Dispose();
            try
            {
                foreach (DirectUIControl c in this.Controls)
                {
                    if (c != null)
                    {
                        c.Dispose();
                    }

                }
            }
            catch(System.Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
        protected virtual IEnumerable<DirectUIControl> GetControls()
        {
            return controls;
        }

        IEnumerable<DirectUIControl> IMultiControlContainer.Controls
        {
            get { return GetControls(); }
        }
        public override void Invalidate()
        {
            if (Initializing || !Visible) return;
            if (Container != null) Container.Invalidate(this.Bounds);
            else if(host!=null)
            {
               
                Host.Invalidate(bounds);
            }
        }
        public virtual void Invalidate(Rectangle bounds)
        {
            if (!Visible) return;
            if (Initializing) return;
            if (Container == null&&host==null) return;

            bounds.Offset(Left, Top);
            // don't let the child control invalidate anything outside the own bounds:
            ClipRectangle(ref bounds);
            if (Container != null)
            {
                Container.Invalidate(bounds);
            }
            else
            {
                Host.Invalidate(bounds);
            }
        }

        //public IHost Host
        //{
        //    get { return Container != null ? this.Container.Host : null; }
        //}
        private IHost host;
        public IHost Host
        {
            get {
                if (this.host != null)
                {
                    return this.host;
                }
                return Container != null ? this.Container.Host : null;
            }
        }
        public void AttachToHost(IHost host){
            Container = null;
            this.host = host;
            this.Font = host.Font;
            this.foreColor = host.ForeColor;
            this.bounds = host.Bounds;
        }
        public System.Drawing.Point PointToHost(int x, int y)
        {
           
                return Host.PointToHost(x + Left, y + Top);
           
        }


        #endregion

        private SizeF defaultSize = new SizeF(1f, 1f);
        protected override void OnSizeChanged(Size oldSize, Size newSize)
        {
            base.OnSizeChanged(oldSize, newSize);
        }


        public override void OnPaint(DirectUIPaintEventArgs e)
        {
            base.OnPaint(e);
            PaintControls(e);
        }

        private bool AreAllControOpaque(DirectUIControlCollection controls)
        {
            bool result = true;
            foreach (DirectUIControl c in controls)
            {
                if (!c.Visible) continue;
                Rectangle r = c.Bounds;
                if (c.Width <= 0 || c.Height <= 0) continue;
                if (c.IsTransparent)
                {
                    result = false;
                    break;
                }
            }
            return result;
        }
        public Bitmap BackGroundImage { get; set; }
        protected override void OnPaintBackground(DirectUIPaintEventArgs e)
        {
            // invalidRegion = e.Graphics.Clip;
            if (BackGroundImage != null)
            {
                Rectangle desRec = e.ControlBounds;
                e.Graphics.DrawImage(BackGroundImage, desRec, new Rectangle(0,0,this.BackGroundImage.Width,this.BackGroundImage.Height), GraphicsUnit.Pixel);
            }
            else
            {
                base.OnPaintBackground(e);
            }
        }
    //    private IList<DirectUIControl> _spei
        /// <summary>
        /// Paints all  controls.
        /// The controls are painted in an optimized way:
        /// The controls are rendered from the last to the first, and after painting each control, the bounds of the control are excluded from the region, so this region is not painted twice.
        /// If a there is a transparent control, the remaining controls are painted from the first to this control, while the region is not excluded.
        /// </summary>
        /// <param name="pe">The PaintEventArgs.</param>
        protected virtual void PaintControls(DirectUIPaintEventArgs pe)
        {
#if true
            Region region = pe.Graphics.Clip;
            Region clip = pe.Region;
            Graphics g = pe.Graphics;
          //  int index = 0;
           for (int i = 0; i <=controls.Count - 1; i++)
          //  for (int i = controls.Count - 1; i >=0 ; i--)
            {
               
                DirectUIControl c = controls[i];
                if (!c.Visible)
                {
                    continue;
                }
                if (c.IsTransparent||c is DirectUIPanel)
                {
                    g.Clip = region;
                }
                Rectangle bounds = PaintControl(pe, c);
                if (!bounds.IsEmpty&&!c.IsTransparent&&!(c is ModalBackground))
                {
                    clip.Exclude(bounds);
                    g.Clip = clip;
                }
                else if (c.IsTransparent || c is DirectUIPanel)
                {
                    g.Clip = clip;
                }
            }
          //  for (int i = 0; i < index; i++)
          //  {
          //      if (i >= controls.Count)
          //      {
          //          return;
          //      }
          //      DirectUIControl c = controls[i];
             
          //          if (c.IsTransparent)
          //          {
          //              pe.Graphics.Clip = region;
          //          }
          //          PaintControl(pe, c);
           
          //  }
          //if (region != null) region.Dispose();

#else
            foreach (DirectUIControl c in controls)
            {
                PaintControl(pe, c);
            }
#endif
        }

        /// <summary>
        /// Paints the control. If the control was painted, the bounds of the rectangle in the canvas are returned, otherwise Rectangle.Empty is returned.
        /// </summary>
        /// <param name="pe">The PaintEventArgs</param>
        /// <param name="control">The control</param>
        /// <returns>If the control was painted, the bounds of the rectangle in the canvas are returned, otherwise Rectangle.Empty is returned.</returns>
        protected virtual Rectangle PaintControl(DirectUIPaintEventArgs pe, DirectUIControl control)
        {
            if (!control.Visible) return Rectangle.Empty;
          
            Rectangle bounds = control.Bounds;
            if (bounds.Width <= 0 || bounds.Height <= 0) return Rectangle.Empty;

            Rectangle controlBounds = pe.ControlBounds;
            Region clip = pe.Region;
            bounds.Offset(controlBounds.X, controlBounds.Y);
            if (clip.IsVisible(bounds))
            {
                PaintControlUnbuffered(pe, control, bounds);
                return bounds;
            }
            return Rectangle.Empty;
        }

        private DirectUIPaintEventArgs paintEventArgs = new DirectUIPaintEventArgs();

        protected void PaintControlUnbuffered(DirectUIPaintEventArgs pe, DirectUIControl control, Rectangle bounds)
        {
            DirectUIPaintEventArgs e = paintEventArgs;
            e.Graphics = pe.Graphics;
            e.ControlBounds = bounds;
            e.Region = pe.Region;
            e.ScaleFactor = pe.ScaleFactor;
            control.OnPaint(e);
        }

        protected DirectUIControl downControl = null;

        protected virtual PointEventArgs TranslatePoint(DirectUIControl c, PointEventArgs p)
        {
            p.X -= c.Bounds.X;
            p.Y -= c.Bounds.Y;
            return p;
        }

        public override void OnGesture(GestureEventArgs e)
        {
            if (!Enabled) return;
            if (downControl != null) downControl.OnGesture(e);

        }

        public override void OnMove(PointEventArgs p)
        {
            if (downControl != null) downControl.OnMove(this.TranslatePoint(downControl, p));
        }


        private DirectUIControl selectedControl;

        public override void OnDown(PointEventArgs p)
        {
            if (!Enabled) return;
            base.OnDown(p);
            DirectUIControl control = ControlFromPoint(p.X, p.Y);
            if (control != null && !control.Active) control = null;
            if (downControl != null&&downControl!=control)
            {
                downControl.OnLostFocus();
            }
            downControl = control;
             selectedControl = control;
            if (control != null)
            {
                PointEventArgs pointEventArgs = TranslatePoint(control, p);
                if (control.Active) control.OnDown(pointEventArgs);
            }
        }

        public override void PerformClick()
        {
            base.PerformClick();
            DirectUIControl control = selectedControl;
            if (control != null)
            {
                if (control.Selectable) Host.FocusedControl = control;
            }
        }

        public override void OnUp(PointEventArgs p)
        {
            base.OnUp(p);
            if (downControl != null) downControl.OnUp(TranslatePoint(downControl, p));
        }

        public override void OnRelease(PointEventArgs p)
        {
            base.OnRelease(p);
            if (downControl != null) downControl.OnRelease(TranslatePoint(downControl, p));
        }
        public override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        {
            if (downControl != null)
            {
                downControl.OnKeyDown(e);
            }
            //if (this.controls != null)
            //{
            //    foreach (DirectUIControl c in this.controls)
            //    {
            //        if (c is ControlContainer && c.Visible)
            //        {
            //            c.OnKeyDown(e);
            //        }
            //    }
            //}
        }
        public override bool OnClick(PointEventArgs p)
        {
            if (!Enabled) return false;
            if (downControl != null) return downControl.OnClick(TranslatePoint(downControl, p));
            base.OnClick(p);
            return false;
        }

        Point p = new Point();

        /// <summary>
        /// Gets the first control that is under the specified point.
        /// </summary>
        /// <param name="x">The x value of the point.</param>
        /// <param name="y">The y value of the point.</param>
        /// <returns>An ITouchControl, otherwise null.</returns>
        /// <remarks>
        /// The enumeration starts from the last to the first control, because the controls appear in this
        /// order in case they are overlapping.
        /// </remarks>
        public virtual DirectUIControl ControlFromPoint(int x, int y)
        {
            p.X = x;
            p.Y = y;
            DirectUIControl result=null;
           for (int i = controls.Count - 1; i >= 0; i--)
     //       for (int i = 0; i <= controls.Count - 1; i++)
            {
                DirectUIControl c = controls[i];
                if (!c.Visible) continue;
                Rectangle r = c.Bounds;
                if (r.Contains(p))
                {
                    result = c;
                    break;            
                }
            }
            return result;
        }

        Rectangle IContainer.GetScreenBounds(Rectangle bounds)
        {
            bounds.Offset(Left, Top);
            if (Container!= null)
            {
                return Container.GetScreenBounds(bounds);
            }
            else
            {
                if (host != null)
                {
                    return host.GetScreenBounds(bounds);
                }
                else
                {
                    return bounds;
                }
            }
        }

        public override bool Active { get { return true; } }

        #region ICommandContainer Members


        public virtual void RaiseCommand(CommandEventArgs e)
        {
            IsDown = false;
            if (Command != null)
            {
                Command(this, e);
            }
            if (!e.Handled)
            {
                ICommandContainer container = this.Container as ICommandContainer;
                if (container != null)
                {
                    container.RaiseCommand(e);
                }
            }
        }

        public virtual event EventHandler Command;

        #endregion

        /// <summary>
        /// Paints a background with a gradient.
        /// </summary>
        /// <param name="e"></param>
        /// <param name="alpha">the alpha value between white and the background color for the starting gradiant color.</param>
        /// <param name="gradientHeight">the height of the gradient until solid color.</param>
        public void PaintGradientBackground(DirectUIPaintEventArgs e, int alpha, int gradientHeight)
        {
            Graphics g = e.Graphics;
            Rectangle r = e.ControlBounds;
            Color color = BackColor;
            Color startColor = ColorConverter.AlphaBlendColor(Color.White, color, alpha);

            Rectangle gr = r;
            gr.Height = gradientHeight;
            GdiExt.GradientFill(g, gr, startColor, color, GdiExt.FillDirection.TopToBottom);
            if (gr.Height < r.Height)
            {
                gr.Y = r.Top + gradientHeight;
                gr.Height = r.Height - gradientHeight;
                using (SolidBrush brush = new SolidBrush(BackColor))
                {
                    g.FillRectangle(brush, gr);
                }
            }

            r.Width--;
            r.Height--;
            using (Pen pen = new Pen(color))
            {
                g.DrawRectangle(pen, r);
            }
        }
        /// <summary>
        /// Paints a background with a gradient.
        /// </summary>
        /// <param name="e"></param>
        public void PaintGradientBackground(DirectUIPaintEventArgs e)
        {
            PaintGradientBackground(e, 50, Height);
        }
        private SizeF scaleFactor = new SizeF(1f, 1f);
        public override void Scale(SizeF scaleFactor)
        {
            if (this.scaleFactor != scaleFactor)
            {
                this.scaleFactor = scaleFactor;
                base.Scale(scaleFactor);
            }
        }

    }
}
